package leecode;

import java.util.Arrays;

/**
 * @author csp 2021-04-28
 */
public class Question16 {
    public int threeSumClosest(int[] nums, int target) {
        int val = Integer.MAX_VALUE;
        int result = Integer.MAX_VALUE;
        int len = nums.length;
        Arrays.sort(nums);
        for (int i = 0; i < len - 2; i++) {
            int p1 = i + 1, p2 = len - 1;
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            while (p1 < p2) {
                int sum = nums[i] + nums[p1] + nums[p2];
                if (sum == target) {
                    return sum;
                } else if (sum < target) {
                    result = target - sum < val ? sum : result;
                    val = Math.min(target - sum, val);
                    while (p1 < p2 && nums[p1] == nums[++p1]) {
                    }
                } else {
                    result = sum - target < val ? sum : result;
                    val = Math.min(val, sum - target);
                    while (p1 < p2 && nums[p2] == nums[--p2]) {
                    }
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Question16 question16 = new Question16();
        final int i = question16.threeSumClosest(new int[]{0,2,1,1,2,0,3,-3}, 1);
        System.out.println(i);
    }
}
